package jnpf.generater.genutil.common;

import jnpf.base.entity.DictionaryDataEntity;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.service.DictionaryDataService;
import jnpf.engine.util.FormCloumnUtil;
import jnpf.engine.entity.FlowEngineEntity;
import jnpf.engine.model.flowengine.FlowEngineModel;
import jnpf.engine.model.flowengine.FlowExportModel;
import jnpf.model.*;
import jnpf.model.visiual.DownloadCodeForm;
import jnpf.model.visiual.FormDataModel;
import jnpf.model.visiual.TableModel;
import jnpf.model.visiual.fields.FieLdsModel;
import jnpf.model.visiual.fields.config.ConfigModel;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import jnpf.util.context.SpringContext;
import jnpf.util.enums.ModuleTypeEnum;
import lombok.Cleanup;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * 功能流程公共工具
 * @author JNPF开发平台组
 * @version V3.2.0
 * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @date  2021/8/25
 */
public class FunctionFormPublicUtil {

	public static FlowExportModel jsonFile(VisualdevEntity entity, DownloadCodeForm downloadCodeForm) {
		List<FormAllModel> formAllModel = new ArrayList<>();
		forDataMode(entity,formAllModel);
		List<FormAllModel> mastList = formAllModel.stream().filter(t -> FormEnum.mast.getMessage().equals(t.getJnpfKey())).collect(Collectors.toList());
		List<FlowEngineModel> tempJson = new ArrayList<>();
		for (FormAllModel mastModel : mastList) {
			FieLdsModel fieLdsModel = mastModel.getFormColumnModel().getFieLdsModel();
			String model =  fieLdsModel.getVModel();
			ConfigModel config = fieLdsModel.getConfig();
			if(StringUtil.isNotEmpty(model)){
				FlowEngineModel engineModel = new FlowEngineModel();
				String label = config.getLabel();
				engineModel.setFiledId(model);
				engineModel.setFiledName(label);
				engineModel.setRequired(false);
				tempJson.add(engineModel);
			}
		}
		List<FormAllModel> tableList = formAllModel.stream().filter(t -> FormEnum.table.getMessage().equals(t.getJnpfKey())).collect(Collectors.toList());
		List<TableModel> tableModelList = JsonUtil.getJsonToList(entity.getTables(),TableModel.class);
		Map<String,String> tableListAll = tableNameRename(downloadCodeForm,tableModelList);
		for (FormAllModel model : tableList) {
			String table = model.getChildList().getTableName();
			String name = tableListAll.get(table);
			FormColumnTableModel childList = model.getChildList();
			String label = childList.getLabel();
			FlowEngineModel engineModel = new FlowEngineModel();
			engineModel.setFiledId(name.toLowerCase()+"List");
			engineModel.setFiledName(label);
			engineModel.setRequired(false);
			tempJson.add(engineModel);
		}
		List<FormAllModel> mastTableList = formAllModel.stream().filter(t -> FormEnum.mastTable.getMessage().equals(t.getJnpfKey())).collect(Collectors.toList());
		for (FormAllModel mastTableModel : mastTableList) {
			FormMastTableModel formMastTableModel = mastTableModel.getFormMastTableModel();
			FieLdsModel fieLdsModel = formMastTableModel.getMastTable().getFieLdsModel();
			String model =  formMastTableModel.getVModel();
			ConfigModel config = fieLdsModel.getConfig();
			if(StringUtil.isNotEmpty(model)){
				FlowEngineModel engineModel = new FlowEngineModel();
				String label = config.getLabel();
				engineModel.setFiledId(model);
				engineModel.setFiledName(label);
				engineModel.setRequired(false);
				tempJson.add(engineModel);
			}
		}
 		FlowEngineEntity engineEntity = flowEngine(entity);
		engineEntity.setFormData(JsonUtil.getObjectToString(tempJson));
		FlowExportModel exportModel = new FlowExportModel();
		exportModel.setFlowEngine(engineEntity);
		exportModel.setVisibleList(new ArrayList<>());
		return exportModel;
	}


	private static FlowEngineEntity flowEngine(VisualdevEntity entity){
		FlowEngineEntity engineEntity = JsonUtil.getJsonToBean(entity,FlowEngineEntity.class);
		engineEntity.setTables("[]");
		engineEntity.setFormType(1);
		engineEntity.setType(1);
		engineEntity.setSortCode(0L);
		engineEntity.setEnabledMark(1);
		engineEntity.setVisibleType(0);
		engineEntity.setIcon("fa fa-file-text-o");
		engineEntity.setFlowTemplateJson(entity.getFlowTemplateJson());
		DictionaryDataService dataService = SpringContext.getBean(DictionaryDataService.class);
		DictionaryDataEntity dataEntity = dataService.getInfo(entity.getCategory());
		engineEntity.setCategory(dataEntity!=null?dataEntity.getEnCode():entity.getCategory());
		return engineEntity;
	}


	/**
	 * 创建文件
	 * @param data
	 * @param path
	 */
	public static void createFile(String data, String path) {
		try {
			File file = new File(path+File.separator+"flow."+ModuleTypeEnum.FLOW_FLOWENGINE.getTableName());
			boolean b = file.createNewFile();
			if(b) {
				@Cleanup Writer out = new FileWriter(file);
				out.write(data);
				out.close();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 封装数据
	 *
	 * @param entity
	 * @param formAllModel
	 */
	private static void forDataMode(VisualdevEntity entity, List<FormAllModel> formAllModel) {
		//formTempJson
		FormDataModel formData = JsonUtil.getJsonToBean(entity.getFormData(), FormDataModel.class);
		List<FieLdsModel> list = JsonUtil.getJsonToList(formData.getFields(), FieLdsModel.class);
		List<TableModel> tableModelList = JsonUtil.getJsonToList(entity.getTables(), TableModel.class);
		RecursionForm recursionForm = new RecursionForm(list,tableModelList);
		FormCloumnUtil.recursionForm(recursionForm, formAllModel);
	}

	public static Map<String,String> tableNameRename(DownloadCodeForm downloadCodeForm, List<TableModel> tableModelList){
		Map<String, String> tableNameMap = new HashMap<>(16);
		int i = 0;
		for (TableModel tableModel : tableModelList) {
			if ("0".equals(tableModel.getTypeId())) {
				String[] subClassName = downloadCodeForm.getSubClassName().split(",");
				tableNameMap.put(tableModel.getTable(), subClassName[i]);
				i++;
			}else {
				tableNameMap.put(tableModel.getTable(),downloadCodeForm.getClassName());
			}
		}
		return tableNameMap;
	}


}
